#!/usr/bin/perl -w
use strict;
use List::Util qw(sum);

my %table;
my %classes;
for my $file ( @ARGV ) {
    unless( $file =~ /(\S+)\.(\d+)\.classes/ ) {
	warn("unknown name of file, cannot parse size in $file\n");
	next;
    }
    my ($base,$size) = ($1,$2);
    $base =~ s/\.out//;
    open(my $fh => $file) || die $!;
    my $i = 0;
    my %header = map { $_ => $i++ } split(/\s+/,<$fh>);
    while(<$fh>) {
	my @row = split;
	my ($class,$total,$samestr,$oppstr) = map { $row[ $header{$_} ] } qw(CLASS COUNTS_TOTAL COUNTS_SAME COUNTS_DIFF);
	next if $class =~ /CDS|mRNA|tRNA_exon/;
	($class) = split(/:/,$class);
	$table{$base}->{$size}->{$class} = [ $total,$samestr,$oppstr];
	$classes{$class}++;
    }
}

my @classes = sort { my ($at,$as) = (split/:/,$a); 
		     my ($bt,$bs) = split(/:/,$b);
		     $bs = $bt unless defined $bs;
		     $as = $at unless defined $as;
		 $as cmp $bs || $at cmp $bt } keys %classes;
while( my ($base,$data) = each %table ) {
    open(my $ofh => ">$base.table") || die "$base.table: $!";
    open(my $ofh_ss => ">$base.table_ss") || die "$base.table_ss: $!";
    open(my $ofh_os => ">$base.table_os") || die "$base.table_os: $!";
    open(my $ofh2 => ">$base.table_percent") || die "$base.table_percent: $!";
    open(my $ofh2_ss => ">$base.table_percent_ss") || die "$base.table_ss_percent: $!";
    open(my $ofh2_os => ">$base.table_percent_os") || die "$base.table_os_percent: $!";

    print $ofh join("\t", qw(SIZE), @classes), "\n";
    print $ofh_ss join("\t", qw(SIZE), @classes), "\n";
    print $ofh_os join("\t", qw(SIZE), @classes), "\n";
    print $ofh2 join("\t", qw(SIZE), @classes), "\n";
    print $ofh2_ss join("\t", qw(SIZE), @classes), "\n";
    print $ofh2_os join("\t", qw(SIZE), @classes), "\n";
    for my $size ( sort { $a <=> $b } keys %$data ) {
	print $ofh join("\t", $size, 
			map { $data->{$size}->{$_}->[0] || 0 } @classes), "\n";
	print $ofh_ss join("\t", $size, 
			map { $data->{$size}->{$_}->[1] || 0 } @classes), "\n";
	print $ofh_os join("\t", $size, 
			map { $data->{$size}->{$_}->[2] || 0 } @classes), "\n";
	my $sum = sum ( map { $data->{$size}->{$_}->[0] || 0 } @classes);
	my $sum_ss = sum ( map { $data->{$size}->{$_}->[1] || 0 } @classes);
	my $sum_os = sum ( map { $data->{$size}->{$_}->[2] || 0 } @classes);
	print $ofh2 join("\t", $size, 
			map { sprintf("%.2f",100*($data->{$size}->{$_}->[0] || 0)/$sum) } @classes), "\n";
	print $ofh2_ss join("\t", $size, 
			map { sprintf("%.2f",100*($data->{$size}->{$_}->[1] || 0)/$sum_ss) } @classes), "\n";
	print $ofh2_os join("\t", $size, 
			map { sprintf("%.2f",100*($data->{$size}->{$_}->[2] || 0)/$sum_os) } @classes), "\n";
    }
}
